package uem

import (
	"io"
	"log"
	"net/http"
	"time"
)

type UemWeb struct {
	controllers *ControllerTables
	addr        string
	handler     http.Server
}

func NewUemWeb(out io.Writer, debug bool, wtm int, rtm int, hrtm int) (*UemWeb, error) {

	web := &UemWeb{}

	web.controllers = NewControllerTables()

	web.handler = http.Server{
		ReadHeaderTimeout: time.Duration(hrtm) * time.Second,
		WriteTimeout:      time.Duration(wtm) * time.Second,
		ReadTimeout:       time.Duration(rtm) * time.Second,
		MaxHeaderBytes:    1 << 20,
		Handler:           NewEngine(debug),
		ErrorLog:          log.New(out, "web", log.LstdFlags),
	}

	return web, nil
}

func (web *UemWeb) AddController(v interface{}) {

	web.controllers.AddController(v)
}

func (web *UemWeb) RegisterController() {

	web.controllers.AllItem(func(value ControllerInterface) {

		router := value.GetControllerName()
		value.SetHttpServer(&web.handler)

		value.GetControllerHandle(router, func(schema string, method string, v interface{}) {
			RegRouterHandlerController(&web.handler, method, schema, v)
		})
	})
}

func (web *UemWeb) Run(addr string) error {

	web.handler.Addr = addr
	return web.handler.ListenAndServe()
}

func (web *UemWeb) HttpClose() error {

	return web.handler.Close()
}

func (web *UemWeb) RunService(ip string, port string) error {

	addr := ip + ":"
	addr += port
	return web.Run(addr)
}
